package fr.umlv.m2.jee.pmlv.web.professor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import fr.umlv.m2.jee.pmlv.persistence.cursus.SpecialtySubject;
import fr.umlv.m2.jee.pmlv.persistence.subject.Project;
import fr.umlv.m2.jee.pmlv.persistence.subject.TD;
import fr.umlv.m2.jee.pmlv.persistence.subject.TP;
import fr.umlv.m2.jee.pmlv.service.planning.DisplayRecordDate;
import fr.umlv.m2.jee.pmlv.service.planning.IDisplayRecordDateService;
import fr.umlv.m2.jee.pmlv.service.user.User;


/**
 * Servlet wich represents event's list of a professor for a week.
 * @author Alexandre
 */
public class ScheduleOfWorksToMake extends HttpServlet {
    // Variables
    private User user = null;   //Contains informations about user
    private List<Integer> years = new ArrayList<Integer>(); //Contains years when professor teaching a subject
    private int currentYear = -1;   //the current year
    private GregorianCalendar monday = null;    //First day of a week concerned
    private GregorianCalendar sunday = null;  //Last day of a week concerned
    private int incrWeek = 0;   //Week concerned
    private List<DisplayRecordDate> works = new ArrayList<DisplayRecordDate>();     //List of works to make for week ocncerned

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ScheduleOfWorksToMake() {
            super();
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response).
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doPost(request,response);
    }

    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response).
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //Data
        user = null;
        years.clear();
        currentYear = -1;
        monday = null;
        sunday = null;
        incrWeek = 0;
        works.clear();

        //Retrieve informations about user
        HttpSession session = request.getSession(true);
        user = (User)session.getAttribute("user");
        years.addAll((List<Integer>)session.getAttribute("years"));
        if(Calendar.getInstance(Locale.FRENCH).get(Calendar.MONTH)>9) currentYear = Calendar.getInstance(Locale.FRENCH).get(Calendar.YEAR);
        else currentYear = Calendar.getInstance(Locale.FRENCH).get(Calendar.YEAR) - 1;

        //Retrieve first day and last of week concerned
        if(request.getParameter("week")!=null)
            incrWeek = Integer.parseInt(request.getParameter("week"));
        monday = new GregorianCalendar(Locale.FRENCH);
        monday.add(Calendar.WEEK_OF_YEAR, incrWeek); monday.add(Calendar.DAY_OF_WEEK, (Calendar.MONDAY - monday.get(Calendar.DAY_OF_WEEK)));
        sunday = new GregorianCalendar(monday.get(Calendar.YEAR),monday.get(Calendar.MONTH),monday.get(Calendar.DATE));
        sunday.add(Calendar.DAY_OF_WEEK, 6);

        //Retrieve event for week concerned
        ServletContext context = getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
        IDisplayRecordDateService workService = (IDisplayRecordDateService) applicationContext.getBean("defautDisplayRecordDateService");
        works.addAll(workService.getRecordDateByWeekAndByProfessorUidAndByYear(monday, user.getuId(), currentYear));
        

        //View
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\" >");

        out.println(" <head>");
        out.println("   <title>PMLV : Portail Universitaire de Marne-La-Vall&eacute;e</title>");
        out.println("   <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />");
        out.println("   <link rel=\"stylesheet\" media=\"screen\" type=\"text/css\" href=\"../css/professor/professor.css\" />");
        out.println("   <link rel=\"stylesheet\" media=\"screen\" type=\"text/css\" href=\"../css/professor/scheduleOfEvents.css\" />");
        out.println(" </head>");

        out.println(" <body>");

        out.println("   <div id=\"header\">");
        out.println("     <ul>");
        out.println("       <li class=\"menuItem menuItemSpacing\"><a href=\"../Professor\">Accueil</a></li>");
        out.println("       <li class=\"menuItem menuItemSpacing\"><a href=\"ListOfStudents\">Listes des &eacute;tudiants</a></li>");
        out.println("       <li class=\"menuItem menuItemSpacing cursor\">Emploi du temps");
        out.println("         <ul class=\"subMenuBar\">");
        out.println("           <li class=\"subMenu\"><a href=\"ScheduleOfCoursesAndExams\">Cours et examens</a></li>");
        out.println("           <li class=\"subMenu\"><a href=\"ScheduleOfWorksToMake\">Rendu de travaux</a></li>");
        out.println("         </ul>");
        out.println("       </li>");
        out.println("       <li class=\"menuItem menuItemSpacing cursor\">Gestion de mati&egrave;re");
        out.println("         <ul class=\"subMenuBar\">");
        for(Integer year:years)
        {
            out.println("           <li class=\"subMenu\"><a href=\"ManagementOfSubjects?year="+year+"\">"+ year +"-"+ (year+1) +"</a></li>");
        }
        out.println("         </ul>");
        out.println("       </li>");
        out.println("       <li id=\"menuItemMargin\" class=\"menuItem\"><a href=\"../j_spring_security_logout\">Se d&eacute;connecter</a></li>");
        out.println("     </ul>");
        out.println("   </div>");

        getDivContent(out, request, response);

        out.println("   <div id=\"footer\">");
        out.println("     <div id=\"copyright\">&copy; Universit&eacute; Paris-Est Marne-la-Vall&eacute;e</div>");
        out.println("     <div>PMLV v1.0 </div>");
        out.println("   </div>");

        out.println(" </body>");

        out.println("</html>");
        out.close();
    }

    /**
     *  Content of page
     */
    private void getDivContent(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
    {
        String str_monday = monday.get(Calendar.DATE) +" "+monday.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRENCH);
        String str_sunday = sunday.get(Calendar.DATE) +" "+sunday.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRENCH);
        ArrayList< ArrayList<Integer> > order = new  ArrayList< ArrayList<Integer> >(7);
        for(int i=0;i<7;i++) {
            order.add( new ArrayList<Integer>());
        }
        for(int i=0;i<works.size();i++) {
            order.get( (works.get(i).getDeadLine().getDay()+7)%8 ).add(new Integer(i));
        }
        int max = order.get(0).size();
        for(ArrayList<Integer> tmp:order) {
            if(max<tmp.size())
                max=tmp.size();
        }


        out.println("   <div id=\"content\">");
        out.println("     <div id=\"title\">Emploi du temps des rendu de travaux </div>");

        out.println("       <table id=\"scheduleTable\">");
        out.println("         <caption>");
        out.println("           <a href=\"ScheduleOfWorksToMake?week="+(incrWeek-1)+"\">&lt;&lt;&nbsp;</a></div>");
        out.println("           Semaine du "+str_monday+" au "+str_sunday);
        out.println("           <a href=\"ScheduleOfWorksToMake?week="+(incrWeek+1)+"\">&nbsp;&gt;&gt;</a>");
        out.println("         </caption>");

        out.println("         <tr>");
        GregorianCalendar tmp = new GregorianCalendar(monday.get(Calendar.YEAR), monday.get(Calendar.MONTH), monday.get(Calendar.DATE));
        String[] day = {"Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi","Dimanche"};
        for(int i=0; i<7; i++)
        {
            out.println("           <th>"+day[i]+"<br/>"+ tmp.get(Calendar.DATE) +" "+tmp.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRENCH) +"</th>");
            tmp.add(Calendar.DAY_OF_WEEK, 1);
        }
        out.println("         </tr>");

        for(int i=0;i<max;i++)
        {
            out.println("         <tr>");
            for(int j=0;j<7;j++)
            {
                if(order.get(j).size()<=i)
                    out.println("           <td> &nbsp </td>");
                else
                {
                    out.println("           <td class=\"event\">");
                    DisplayRecordDate work = works.get( order.get(j).get(i) );
                    String type = "";
                    if(work.getTheme() instanceof TP) type="TP";
                    else if(work.getTheme() instanceof TD) type="TD";
                    else if(work.getTheme() instanceof Project) type="Projet";
                    String cursus = "";
                    for(SpecialtySubject spesub:work.getTheme().getSubject().getSpecialtySubject())
                    {
                        cursus = spesub.getSpecialty().getCursus().getName();
                    }
                    String heure = "";
                    if(work.getDeadLine().getHours()/10==0) heure = "0"+work.getDeadLine().getHours()+"h";
                    else heure = work.getDeadLine().getHours()+"h";
                    if(work.getDeadLine().getMinutes()/10==0) heure = heure+"0"+work.getDeadLine().getMinutes();
                    else heure = heure+""+work.getDeadLine().getMinutes();
                    out.println("               "+cursus+"<br/>"+type+" "+work.getTheme().getSubject().getAbbreviation()+"<br/> <u>Limite :</u> "+heure);
                    out.println("           </td>");
                }
            }
            out.println("         </tr>");
        }
        out.println("       </table>");

        if(works.isEmpty())
            out.println("       <center>Aucun travaux &agrave; faire cette semaine.</center>");

        out.println("   </div>");
    }
}
